package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.pojo.NutritionInfo;
import org.example.pojo.Respw;
import org.example.pojo.Result;
import org.example.utils.ApiUtils;
import org.example.utils.MultipartFileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/onlineapi")
@Slf4j
public class ApiController {
    @Value("${file.photo-path}")
    private String photoPath;

    @Autowired
    private ApiUtils apiUtils;

    @PostMapping("/putonline") //3秒多
//    @Transactional(timeout = -1)
    public Result<String> putonline(@RequestParam("file") MultipartFile file,@RequestParam("userId") int userId) {
//        log.info("userId="+userId);
        String local_file_path=MultipartFileUtils.saveMultipartFile(file,photoPath,"photo",userId);
        log.info("local_file_path=" + local_file_path);
        if(local_file_path.startsWith("Error:")){
            return Result.error(local_file_path.substring(6));
        }
        // 使用replace方法将单斜杠替换为双斜杠
        local_file_path = local_file_path.replace("\\", "\\\\");

//        File destFile=new File("");
//        try {
//            //一、
//            // 1.检查文件
//            if (file.isEmpty()) {
////                return new Response(false, "获取录音失败", (List<String>) file);
//                return Result.error("获取食谱图片失败");
//            }
//            // 2.生成新文件名
//            String originalFilename = file.getOriginalFilename();
//            String suffix = originalFilename.substring(originalFilename.lastIndexOf("."));
//            String newFileName = UUID.randomUUID().toString() + suffix;
//            // 3.创建保存目录
//            String datePath = new SimpleDateFormat("yyyy/MM/dd").format(new Date());        //当前日期 加上2024/12/7
//            log.info("datePath=" + datePath);
//            //    url组成     E盘前缀  +username   + 创建时间   +文件名
//            File photoUrl = new File(photoPath + "/photo/" + userId + "/" + datePath);         //切割后的文件夹路径
//            log.info("photoUrl=" + photoUrl);
//            if (!photoUrl.exists()) {
//                photoUrl.mkdirs();      //要创建下面才能正常执行
//            }
//            // 4.保存文件
//            destFile = new File(photoUrl, newFileName);
//            file.transferTo(destFile);
//        }  catch (Exception e) {
//            e.printStackTrace();
////            return "文件上传失败：" + e.getMessage();
//        }
//        String local_file_path=destFile.getAbsolutePath();
//        log.info("local_file_path=" + local_file_path);



        String online_file_path="";

        try { //执行到第三步时就超时了
            String file_id=apiUtils.uploadImage(local_file_path);
            Thread.sleep(500);
            String[] dialog_id=apiUtils.initiateChat(file_id);
            Thread.sleep(1000);
            online_file_path=apiUtils.getChatMessages(dialog_id[0],dialog_id[1]);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("扣子api请求失败："+e.getMessage());
        } catch (InterruptedException e) {
            e.printStackTrace();
            return Result.error("扣子api请求超时："+e.getMessage());
        }

        log.info(online_file_path);
        return Result.success(online_file_path);
    }

    @PostMapping("/agent") //8秒多
//    @Transactional(timeout = -1)
//    public Result<NutritionInfo> agent(@RequestParam("image_url") String image_url) { //前端是用http.ts封装的请求，不能用
//    public Result<NutritionInfo> agent(@RequestBody String image_url) { //前端发送的 askAgentForm.value 是一个对象，不是单一值
    public Result<NutritionInfo> agent(@RequestBody Map<String, String> requestBody) {
        try {
            String image_url = requestBody.get("image_url");
            NutritionInfo nutritionInfo=apiUtils.analyzeNutrition(image_url);
            log.info("nutritionInfo=" + nutritionInfo);
            return Result.success(nutritionInfo);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("扣子api请求失败："+e.getMessage());
        }
    }
}
